package com.jp.fm.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jp.fm.HomeFinanceRunner;
import com.jp.fm.dao.AccountDao;
import com.jp.fm.data.Account;

public class SaveAccounts extends ServletParent {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public SaveAccounts() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public final void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public final void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {

		doPost(request, response);
	}

	public final void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {

		String showAll = request.getParameter("showAll");
		String hideAccount = request.getParameter("hide");
		if (null != showAll && "true".equals(showAll)) {
			List<Account> accounts = getAccountDao().findAll();
			for (Account account : accounts) {
				if (account.isHidden()) {
					account.setHidden(false);
					getAccountDao().writeObject(account);
				}
			}

			// Clear the account cache
			HomeFinanceRunner.getCache(AccountDao.CACHE_NAME).removeAll();
		} else if (null != hideAccount) {
			Account account = getAccountDao().findByName(hideAccount);
			account.setHidden(true);
			getAccountDao().writeObject(account);

			// Clear the account cache
			HomeFinanceRunner.getCache(AccountDao.CACHE_NAME).removeAll();
		}

		String[] opens = request.getParameterValues("o");
		if (null != opens) {
			request.setAttribute("o", Arrays.asList(opens));
		}

		RequestDispatcher rd = request
				.getRequestDispatcher("/secured/ShowAccountSummary");
		rd.forward(request, response);
	}
}
